﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using NAudio.Wave;
using SynoManager.AudioStation.Data;

namespace SynoManager.AudioStation
{
    public class StreamPlayer
    {
        private readonly AudioStationService service;
        private MusicFile file;

        public event EventHandler StartPlaying;
        public event EventHandler StopPlaying;

        public event EventHandler BlockDownloaded;
        public event EventHandler DownloadComplete;

        public StreamPlayer(AudioStationService service)
        {
            this.service = service;
        }

        public MusicFile CurrentFile
        {
            get { return file; }
        }

        public void Play(MusicFile file)
        {
            string songpath = file.Path;
            this.file = file;
            string url = service.client.ServiceLocation;
            url += "?action=streaming&songpath=" + songpath;
            Play(url);
        }

        public void Pause()
        {
        }

        private void Play(string url)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                using (Stream stream = WebRequest.Create(url)
                    .GetResponse().GetResponseStream())
                {
                    byte[] buffer = new byte[32768];
                    int read;
                    while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        ms.Write(buffer, 0, read);
                    }
                }

                ms.Position = 0;

                using (WaveStream blockAlignedStream =
                    new BlockAlignReductionStream(
                        WaveFormatConversionStream.CreatePcmStream(
                            new Mp3FileReader(ms))))
                {
                    using (WaveOut waveOut = new WaveOut(0, 500, false))
                    {
                        waveOut.Init(blockAlignedStream);
                        waveOut.Play();
                        while (blockAlignedStream.Position < blockAlignedStream.Length)
                        {
                            System.Threading.Thread.Sleep(100);
                        }
                    }
                }
            }
        }
    }
}